package com.itheima.web.servlet.base;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author Xiao
 * @date 2021/9/9
 */
public class BaseServlet extends HttpServlet {
    @Override
    //根据请求路径的最后一段的方法名，执行对应方法
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求路径
        String uri = req.getRequestURI();// uri --> /brandCase/brand/add
        //2. 获取最后一段请求路径，即方法名
        int index = uri.lastIndexOf("/"); // index --> 最后一个"/"对应的索引
        //String methodName = uri.substring(index);// --> /add
        String methodName = uri.substring(index + 1);// --> add
        //3. 执行方法 --> 反射
        //获取BrandServlet字节码对象
        Class<? extends BaseServlet> clazz = this.getClass();
        //获取方法Method对象，执行方法method.invoke()
        try {
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        }catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
